package com.example.redis.service;

import com.example.common.service.TestService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Service
public class RedisTestService implements TestService {

    private static final String LOCK_OF_LOCK_CONTROLLER = "LOCK_OF_LOCK_CONTROLLER";

    private final RLock lock;

    private final RedisOperations<String, Serializable> redisOperations;

    @Autowired
    public RedisTestService(RedissonClient redissonClient, RedisOperations<String, Serializable> redisOperations) {
        this.lock = redissonClient.getLock(LOCK_OF_LOCK_CONTROLLER);
        this.redisOperations = redisOperations;
    }

    @Override
    public Object doTest(Object param) {
        return null;
    }

    private void test(){
        Serializable serializable = null;
        try{
            //l是获取锁等待时间， l1是持有锁时间，超过时间就会自动释放锁。
            boolean locked = lock.tryLock(500L, 15000L, TimeUnit.MILLISECONDS);
            if (locked){
                serializable = redisOperations.opsForValue().get("tainn");
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            if (lock != null && lock.isLocked() && lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
        System.out.println(serializable);
    }

    private void test2(){
        //这个操作在redis生成的是"\"hello, tainn\""  而不是 “hello, tainn”
        redisOperations.opsForValue().set("tainn", "hello, tainn");//如果不是与客户端相同序列化插入的 则无法反序列化
        //if not Serializable  JsonParseException: Unrecognized token 'nihao': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
        Object obj = redisOperations.opsForValue().get("tainn");
    }
}
